package com.example.order.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

@Configuration
public class DelayConfig implements Ordered {
    @Override
    public int getOrder() {
        return -100;
    }

    //延迟队列的名字
    public final static String DELAY_QUEUE_PER_QUEUE_TTL_NAME = "delay_coupon_ttl_queue";
    //工作队列的名字
    public final static String DELAY_PROCESS_QUEUE_NAME = "delay_coupon_progress";
    //死信交换机的名字
    public final static String DELAY_EXCHANGE_NAME = "delay_exchange";

    //创建接收延时消息队列
    @Bean
    Queue delayQueuePerQueueTTL() {
        //使用队列构造器创建queue对象
        return QueueBuilder.durable(DELAY_QUEUE_PER_QUEUE_TTL_NAME)//绑定死信队列
                .withArgument("x-dead-letter-exchange", DELAY_EXCHANGE_NAME)//绑定死信交换机
                .withArgument("x-dead-letter-routing-key", DELAY_PROCESS_QUEUE_NAME)//绑定死信路由(工作队列的名字)
                .build();
    }

    /**
     * 工作队列
     * @return 工作队列
     */
    @Bean
    Queue delayProcessQueue(){
        return QueueBuilder.durable(DELAY_PROCESS_QUEUE_NAME).build();
    }

    /**
     * 创建死信交换机
     * @return 返回死信交换机
     */
    @Bean
    DirectExchange delayExchange(){
        return new DirectExchange(DELAY_EXCHANGE_NAME);
    }
    /**
     * 配置绑定关系
     * @param delayProcessQueue 工作队列
     * @param delayExchange 死信交换机
     * @return 绑定关系
     */
    @Bean
    Binding delayBinding(Queue delayProcessQueue, DirectExchange delayExchange){
        //将工作队列绑定到死信交换机
        return BindingBuilder.bind(delayProcessQueue)
                .to(delayExchange)
                .with(DELAY_PROCESS_QUEUE_NAME);
    }
}
